//
//  DaPeiViewController.m
//  Cooking

//  Created by dlios on 15-10-9.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "DaPeiViewController.h"
#import "DaPeiCollectionViewCell.h"
#import "AsyncGetConnection.h"
#import "DaPeiModel.h"
#import "DaPeiClassfileModel.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "ClassfileTableViewCell.h"
#import "SearchModel.h"
#import "ChooseCollectionViewCell.h"
#import "SearchDetailViewController.h"
#import "MyFoodDaPei.h"
@interface DaPeiViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MBProgressHUDDelegate,UITableViewDataSource ,UITableViewDelegate>
{
    int pageNumber; //加载网址中的page数
}
@property(nonatomic ,retain)UICollectionView *collectView;
@property(nonatomic ,retain)NSMutableArray *collectArray;
@property(nonatomic ,retain)NSMutableArray *ClassfileArray; // 右边tableview的数组
@property(nonatomic ,retain)MBProgressHUD *HUD;
@property(nonatomic ,retain)UITableView *tableView;
@property(nonatomic ,retain)UIImageView *imagev; // 右边按钮
@property(nonatomic ,retain)NSMutableArray *playArray;  //collect 的赋值数组
@property(nonatomic ,copy  )NSString *kind;  //是否被选中
@property(nonatomic ,assign)NSInteger number; // 选中哪一个
@property(nonatomic ,retain)NSMutableArray *chooseArray;  // 选的菜
@property(nonatomic ,retain)UIAlertView *alert; // 提示
@property(nonatomic ,retain)UIAlertView *alert1;
@property(nonatomic ,retain)UIView *downView; //最下面的view
@property(nonatomic ,retain)UIView *downView2; //最下面的view
@property(nonatomic ,retain)UILabel *alabel; //最下面的view上的label
@property(nonatomic ,retain)NSMutableArray *findArray; // 查到的菜
@property(nonatomic ,retain)UICollectionView *chooseCollectView; //查到菜的collectview
@property(nonatomic ,retain) UILabel *hintLabel; //未找到菜谱的 提示
@property(nonatomic ,retain)NSMutableArray *recodArray; //记录选中的食材的items值
@property(nonatomic ,assign)NSInteger tableCellRow; // 记录哪一个tableview的cell
@property(nonatomic ,retain)NSMutableArray *buttonArray; //存储创建的Button 以便下面的collectView和DowenView偏移上去,取出他上面的"x"label
@property(nonatomic ,retain) UIAlertView *alertBack;//提示按返回键
@property(nonatomic ,retain)UIButton *sureButton ; // 确定button

@end

@implementation DaPeiViewController

- (void)dealloc
{
    [_sureButton release];
    pageNumber = 1;
    [_alertBack release];
    [_buttonArray release];
    [_recodArray release];
    [_hintLabel release];
    [_chooseCollectView release];
    [_alert release];
    [_downView release];
    [_downView2 release];
    [_alert release];
    [_alert1 release];
    [_chooseArray release];
    [_kind release];
    [_playArray release];
    [_imagev release];
    [_tableView release];
    [_HUD release];
    [_ClassfileArray release];
    [_collectArray release];
    [_collectView release];
    [super dealloc];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
     
        self.buttonArray = [NSMutableArray array];
        self.tableCellRow = 0; //起始为0
        self.recodArray = [NSMutableArray array];
        self.chooseArray = [NSMutableArray array];
        self.findArray = [NSMutableArray array];
        self.collectArray = [NSMutableArray array];
        self.ClassfileArray = [NSMutableArray array];
        self.playArray = [NSMutableArray array];
        self.number = 0; // 0时正常赋值
        pageNumber = 1;//菜谱的page 网址参数
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
      self.navigationItem.title = @"食材搭配";
    [self creat];
    [self startConnect];
    [self creatLoad];
    [self creatTableView];
    [self  creatMyButton];
    [self creatChooseCollectView];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
// 创建tableView
-(void)creatTableView
{
    self.tableView = [[[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, 150, self.view.frame.size.height - 40 -64) style:UITableViewStylePlain]autorelease];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
}
// 创建侧边button
-(void)creatMyButton
{
    self.imagev = [[[UIImageView alloc]initWithFrame: CGRectMake(self.view.frame.size.width - 30, (self.view.frame.size.height - 64 ) / 2.0f , 30, 40)]autorelease];
    _imagev.image = [UIImage imageNamed:@"zheQi.png"];
    [self.view addSubview:_imagev];
    self.imagev.layer.borderWidth = 0.3;
    self.imagev.layer.cornerRadius = 5;
    self.imagev.layer.borderColor = [[UIColor grayColor]CGColor];
    self.imagev.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGester = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesterAction:)]autorelease];
    [_imagev addGestureRecognizer:tapGester];
    
}

-(void)tapGesterAction:(id)sender
{
    NSLog(@"000000pp%f",self.tableView.frame.origin.x);
    NSLog(@"kk%f",self.view.frame.size.width);
    NSString *str1 = [NSString stringWithFormat:@"%.0lf",self.tableView.frame.origin.x];
    NSString *str2 = [NSString stringWithFormat:@"%.0lf",self.view.frame.size.width];
    
    BOOL myhh = [str1 isEqualToString:str2];
    NSLog(@"%d",myhh);
    if (myhh) {
        [UIView animateWithDuration:1.0f animations:^{
            self.tableView.frame = CGRectMake(self.view.frame.size.width-150, 0, 150, self.view.frame.size.height - 40);
            self.imagev.frame = CGRectMake(self.view.frame.size.width - 30 - 150, (self.view.frame.size.height) / 2.0f  , 30, 40);
            self.collectView.userInteractionEnabled = NO;
            self.collectView.alpha = 0.5;
            _imagev.image = [UIImage imageNamed:@"zhanKai.png"];
        }];
       
    }else
    {
        [UIView animateWithDuration:1.0f animations:^{
            self.tableView.frame = CGRectMake(self.view.frame.size.width, 0, 150, self.view.frame.size.height  - 40);
            self.imagev.frame = CGRectMake(self.view.frame.size.width - 30, (self.view.frame.size.height) / 2.0f , 30, 40);
        }];
        self.collectView.userInteractionEnabled = YES;
        self.collectView.alpha = 1;
          _imagev.image = [UIImage imageNamed:@"zheQi.png"];
    }
}


// 创建加载图
-(void)creatLoad
{
    self.HUD = [[[MBProgressHUD alloc] init]autorelease];
    _HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
    _HUD.delegate = self;
    _HUD.backgroundColor = [UIColor clearColor];
    _HUD.detailsLabelText = @"努力加载中...";
    _HUD.dimBackground = YES;
}

// 创建collectView
-(void)creat
{
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc]init]autorelease];
    layout.itemSize = CGSizeMake((self.view.frame.size.width-25)/4.0-10, (self.view.frame.size.width)/4.0+10);
    
    self.collectView = [[[UICollectionView alloc]initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-25, self.view.frame.size.height - 40 -64) collectionViewLayout:layout]autorelease];
    [self.view addSubview:self.collectView];
    self.collectView.backgroundColor = [UIColor whiteColor];
    self.collectView.delegate = self;
    self.collectView.dataSource = self;
    self.collectView.showsVerticalScrollIndicator = NO;
    
    [self.collectView registerClass:[DaPeiCollectionViewCell class] forCellWithReuseIdentifier:@"dapei"];
    
    self.downView = [[[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 40 -64, self.view.frame.size.width, 40)]autorelease];
    _downView.layer.borderWidth = 0.3;
    [self.view addSubview: self.downView];
    
    self.alabel = [[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)]autorelease];
    _alabel.backgroundColor = [UIColor whiteColor];
    [self.downView addSubview:_alabel];
    _alabel.text = @"选择两种或三种食材,就会知道可以做那些菜";
    _alabel.layer.borderWidth = 0.3;
    _alabel.textAlignment = NSTextAlignmentCenter;
}

// choose后弹上来的 collectView
-(void)creatChooseCollectView
{
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc]init]autorelease];
    layout.itemSize = CGSizeMake((self.view.frame.size.width ) / 3.0f, 140);
    layout.minimumInteritemSpacing = 0;
    
    self.chooseCollectView = [[[UICollectionView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 100) collectionViewLayout:layout]autorelease];
    [self.chooseCollectView registerClass:[ChooseCollectionViewCell class] forCellWithReuseIdentifier:@"choose"];
    _chooseCollectView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_chooseCollectView];
    self.chooseCollectView.delegate = self;
    self.chooseCollectView.dataSource = self;
    
    [self.chooseCollectView addHeaderWithCallback:^{
        
        [self connectionOfFoodBook:@"1"];
        pageNumber = 1;
        
    }];
    [self.chooseCollectView addFooterWithCallback:^{
        pageNumber++;
        NSString *mypage = [NSString stringWithFormat:@"%d",pageNumber];
        [self connectionOfFoodBook:mypage];
        
    }];
}

// 网络请求
-(void)startConnect
{
    NSMutableDictionary *strDic = [NSMutableDictionary dictionary];
    [strDic setObject:@"MaterialSubtype" forKey:@"methodName"];
    [strDic setObject:@"version" forKey:@"4.02"];
    //?methodName=MaterialSubtype&version=4.02&
    [AsyncGetConnection asyncPOSTConnectionWithURL:@"http://api.izhangchu.com" parameters:strDic block:^(NSData *data) {
        [self.ClassfileArray removeAllObjects];
        [self.collectArray removeAllObjects];
        [self.playArray removeAllObjects];

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        NSArray *dataArr= [dataDic objectForKey:@"data"];
        for (int i = 0; i < dataArr.count ; i++) {
            NSDictionary *dic = [dataArr objectAtIndex:i];
            DaPeiClassfileModel *model = [[DaPeiClassfileModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            model.Id = [dic objectForKey:@"id"];
            model.text = [dic objectForKey:@"text"];
            model.image = [dic objectForKey:@"image"];
            model.data = [dic objectForKey:@"data"];

            [self.ClassfileArray addObject:model];
            NSArray *dapeiData = [dic objectForKey:@"data"];
             NSMutableArray  *smallArr = [NSMutableArray array];
            for (int j = 0; j < dapeiData.count; j++) {
                NSDictionary *mydic = [dapeiData objectAtIndex:j];
                DaPeiModel *myModel = [[DaPeiModel alloc]init];
                [myModel setValuesForKeysWithDictionary:mydic];
                [smallArr addObject:myModel];
             }
            [self.collectArray addObject:smallArr];
            NSMutableArray *smallRecodArray = [NSMutableArray array];
            [self.recodArray addObject:smallRecodArray];
            
        }
        [self.playArray addObjectsFromArray:[_collectArray objectAtIndex:0]];
        [self.collectView reloadData];
        [self.tableView reloadData];
        [_HUD hide:YES];
    }];
    
}

-(NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.chooseCollectView) {
        return self.findArray.count;
    }
    return self.playArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
  if (collectionView == self.chooseCollectView) {
      ChooseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"choose" forIndexPath:indexPath];
          if (self.findArray.count != 0) {
              [cell receveModel:[self.findArray objectAtIndex:indexPath.item] ];
          }

           return cell;
     }else
     {
          DaPeiCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dapei" forIndexPath:indexPath];
         if (self.collectArray.count != 0) {
             if (self.number == 0) {
                 DaPeiModel *model = [self.playArray  objectAtIndex:indexPath.item];
                 [cell receveModel:model type:@""];
                 self.number ++;
             }
         BOOL judegChoose = NO;
         NSMutableArray *smallRecodArr = [self.recodArray objectAtIndex:self.tableCellRow];
         for (int i = 0; i < smallRecodArr.count; i++) {
             NSInteger myinteger =  [[[smallRecodArr objectAtIndex:i] objectForKey:@"number"] integerValue];             if (myinteger == indexPath.item) {
                 judegChoose = YES; //循环判断是否 选中
              }
             }
                 if (judegChoose) {
                     DaPeiModel *model = [self.playArray  objectAtIndex:indexPath.item];
                     [cell receveModel:model type:@"1"];

                 }else
                 {
                      DaPeiModel *model = [self.playArray  objectAtIndex:indexPath.item];
                      [cell receveModel:model type:@"2"];
                 }
          }
           return cell;
    }
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectView) {
        _number = indexPath.row;
            BOOL judgeHave = NO;  //判断下面有没有选 这个菜
            DaPeiModel *daPeimodel = [self.playArray  objectAtIndex:indexPath.item];
            for (int i = 0 ; i < self.chooseArray.count; i++) {
             NSMutableDictionary *myReocdDic = [self.chooseArray objectAtIndex:i];
                DaPeiModel *amodel = [myReocdDic objectForKey:@"model"];
                
               if([amodel.Id isEqualToString:daPeimodel.Id]) {
                   judgeHave = YES; //如果有了,变为YES
                   //因为有 ,把这个从数组里移除
                   [self.chooseArray removeObjectAtIndex:i];
                }
            }
        
         if (judgeHave) {
            self.kind = @"2"; //让这个cell 变成可编辑状
             NSMutableArray *smallRecodArr =  [self.recodArray objectAtIndex:self.tableCellRow];
            for (int i = 0; i < smallRecodArr.count; i++) {
                NSInteger num = [[[smallRecodArr objectAtIndex:i] objectForKey:@"number"] integerValue];
                
                if (indexPath.item == num) {
                    [smallRecodArr removeObjectAtIndex:i];
                }
            }
         }
         else
          {
            if (self.chooseArray.count < 3) {
                  self.kind = @"1"; //让这个cell 变成不可编辑状态
                NSMutableDictionary *recodDic = [NSMutableDictionary dictionary];
                  DaPeiModel *model = [_playArray objectAtIndex:indexPath.row];
                [recodDic setObject:model forKey:@"model"];   // 存入选中的item 所在的 model
                NSNumber *anum = [NSNumber numberWithInteger:self.tableCellRow];
                [recodDic setObject:anum forKey:@"cellRow"]; // 存入tableViewCell.Row的记录
                  [self.chooseArray  addObject:recodDic];
                
                NSMutableDictionary *myDic = [NSMutableDictionary dictionary];
                NSNumber *numb = [NSNumber numberWithInteger:indexPath.item];
                [myDic setObject:numb forKey:@"number"];
                [myDic setObject:model forKey:@"model"];
                NSMutableArray *smallRecodArr = [self.recodArray objectAtIndex:self.tableCellRow];
                  [smallRecodArr addObject:myDic];
              }else
              {
//               [self.chooseArray removeLastObject];
                  self.alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"亲,最多只能选三种!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                  [self.alert show];
                  [NSTimer scheduledTimerWithTimeInterval:0.75f target:self selector:@selector(timeAction) userInfo:nil repeats:NO];
              }
          }
          if (self.chooseArray.count != 0) {
                [self.alabel removeFromSuperview];
                [self.downView2 removeFromSuperview];
                self.downView2 = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)]autorelease];
                [self.downView addSubview:self.downView2];
                _downView2.backgroundColor = [UIColor whiteColor];
              
              // 创建选中食材的button
              [self creatFoodBotton];
              // 创建sureButton
              [self creatSureButton];
              [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
              
            }else
            {
                // 如果没选择的食材,显示下面的label
                [self.downView2 removeFromSuperview];
                self.alabel = [[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)]autorelease];
                _alabel.backgroundColor = [UIColor whiteColor];
                [self.downView addSubview:_alabel];
                _alabel.text = @"选择两种或三种食材,就会知道可以做那些菜";
                _alabel.layer.borderWidth = 0.3;
                _alabel.textAlignment = NSTextAlignmentCenter;
            }
        
            [self.collectView reloadData];
     }
    else
      {
            SearchDetailViewController *search = [[[SearchDetailViewController alloc]init]autorelease];
            [search receveSearchModel:[self.findArray objectAtIndex:indexPath.item]];
            [self.navigationController pushViewController:search animated:NO];
            
        }
}
// 创建选中食材的button
-(void)creatFoodBotton
{     [self.buttonArray removeAllObjects]; //清空要存入Button的数组
    for (int i = 0; i < self.chooseArray.count; i++) {
        // 用自定义Button ,作用是利用button的属性 记录这个button是哪个tableview的cell里的,以便点击button是找到tableViewcell 的记录数组,删除这项纪录,让cell上的选中图片取消,变成可编辑状态
//         [self.downView addSubview:self.downView2];
        MyFoodDaPei *abutton = [MyFoodDaPei buttonWithType:UIButtonTypeCustom];
        abutton.frame = CGRectMake(i * 70 + 10, 5, 60, 30);
        [self.downView2 addSubview:abutton];
        // 把点击的这个cell(或者点击后创建的button)是哪个tableView里的 写入button的属性
        NSMutableDictionary *recodDic = [_chooseArray objectAtIndex:i];
        abutton.TableviewCellRow = [[recodDic objectForKey:@"cellRow"]integerValue];
        DaPeiModel *mymodel = [recodDic objectForKey:@"model"];
        abutton.layer.cornerRadius = 5;
        abutton.titleLabel.font = [UIFont systemFontOfSize:12];
        [abutton setTitle:mymodel.text forState:UIControlStateNormal];
        [abutton addTarget:self action:@selector(chooseButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        abutton.backgroundColor = [UIColor orangeColor];
        
        UILabel  *cancelLabel = [[[UILabel alloc]initWithFrame:CGRectMake(abutton.frame.size.width-10, 0, 10, 10)]autorelease];
        cancelLabel.layer.cornerRadius = 10;
        cancelLabel.text = @"x";
        cancelLabel.textAlignment =NSTextAlignmentCenter;
        cancelLabel.textColor = [UIColor whiteColor];
        [abutton addSubview:cancelLabel];
        
        //把button存到数组中
        [self.buttonArray addObject:abutton];
    }
}
//创建确定 button
-(void)creatSureButton
{
    self.sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.downView2 addSubview:_sureButton];
    _sureButton.layer.cornerRadius = 5;
    _sureButton.backgroundColor = [UIColor redColor];
    _sureButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _sureButton.frame = CGRectMake(self.view.frame.size.width - 60, 5, 50, 30);
    [_sureButton addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];

}

// 定时器 事件
-(void)timeAction
{
    [self.alert dismissWithClickedButtonIndex:0 animated:NO];
    [self.alert1 dismissWithClickedButtonIndex:0 animated:NO];
}
// 最下面被选中菜的  点击事件
-(void)chooseButtonAction:(MyFoodDaPei *)sender
{
    NSString *str1 = [NSString stringWithFormat:@"%.0lf",self.downView.frame.origin.y];
    NSString *str2 = [NSString stringWithFormat:@"%.0lf",0.0];
    if ([str1 isEqualToString:str2]) {
        self.alertBack = [[[UIAlertView alloc]initWithTitle:@"提示" message:@"请点击返回" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil]autorelease];
        [_alertBack show];
        [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(backMessageAction:) userInfo:nil repeats:NO];
    }else
    {
    // 从数组中 删除选中的菜
    for (int i = 0; i < self.chooseArray.count; i++) {
        NSMutableDictionary *myReocdDic = [self.chooseArray objectAtIndex:i];
        DaPeiModel *mymodel = [myReocdDic objectForKey:@"model"];
        if ([mymodel.text isEqualToString:sender.titleLabel.text]) {
            [self.chooseArray removeObjectAtIndex:i];
        }
     }
        //根据button的属性记录找出这个Button是哪个tableView cell里的 记录中 是否有下面选中的
        NSMutableArray *smallRecodArr = [self.recodArray objectAtIndex:sender.TableviewCellRow];
        for (int i = 0; i < smallRecodArr.count; i++) {
            DaPeiModel *mymodel = [[smallRecodArr objectAtIndex:i] objectForKey:@"model"];
            if ([mymodel.text isEqualToString:sender.titleLabel.text]) {
                [smallRecodArr removeObjectAtIndex:i];
                [self.collectView reloadData];
            }
        }
    // 在downView上 铺新的菜(button)
    [self.downView2 removeFromSuperview];
    self.downView2 = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)]autorelease];
    _downView2.backgroundColor = [UIColor whiteColor];
    [self.downView addSubview:self.downView2];
        // 创建选种食材的button
        [self creatFoodBotton];
//
//    if (self.chooseCollectView.frame.origin.y == self.view.frame.size.height) {
//        
//        [self creatSureButton];
//        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
//    }else
//    {
//        [self creatSureButton];
//        [_sureButton setTitle:@"返回" forState:UIControlStateNormal];
//    }
        // 创建确定Button
        [self creatSureButton];
        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];

          if (self.chooseArray.count == 0) {
            [self.downView2 removeFromSuperview];
            self.alabel = [[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)]autorelease];
            _alabel.backgroundColor = [UIColor whiteColor];
            [self.downView addSubview:_alabel];
            _alabel.text = @"选择两种或三种食材,就会知道可以做那些菜";
            _alabel.layer.borderWidth = 0.3;
            _alabel.textAlignment = NSTextAlignmentCenter;
              [UIView animateWithDuration:1.0f animations:^{
                  self.downView.frame = CGRectMake(0, self.view.frame.size.height - 40 , self.view.frame.size.width, 40);
                  self.chooseCollectView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 100);
                  self.collectView.userInteractionEnabled = YES;
                  self.collectView.alpha = 1;
              }];
        }
    }
  
}
// 提示按返回键
-(void)backMessageAction:(id)sender
{
    [self.alertBack dismissWithClickedButtonIndex:0 animated:YES ];
}
// 确定点击方法
-(void)sureAction:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"返回"]) {
        [UIView animateWithDuration:1.0f animations:^{
            for (int i = 0; i < self.buttonArray.count; i++) {
                MyFoodDaPei *abutton = [self.buttonArray objectAtIndex:i];
                for (id alabel in [abutton subviews]) {
                    if ([alabel isKindOfClass:[UILabel class]]) {
                        UILabel *findLabel = (UILabel *)alabel;
                        if ([findLabel.text isEqualToString:@"x"]) {
                            [findLabel removeFromSuperview];
                        }
                    }
                }

                UILabel *cancelLabel = [[[UILabel alloc]initWithFrame:CGRectMake(abutton.frame.size.width-10, 0, 10, 10)]autorelease];
                cancelLabel.layer.cornerRadius = 10;
                cancelLabel.text = @"x";
                cancelLabel.textAlignment =NSTextAlignmentCenter;
                cancelLabel.textColor = [UIColor whiteColor];
                [abutton addSubview:cancelLabel];
            }
            self.downView.frame = CGRectMake(0, self.view.frame.size.height - 40 , self.view.frame.size.width, 40);
            self.chooseCollectView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 100);
            [sender setTitle:@"确定" forState:UIControlStateNormal];
            self.collectView.userInteractionEnabled = YES;
            self.collectView.alpha = 1;
        }];
    }else
    {
        // 数组里的元素大在两个以上 执行请求,等一些列操作
      if (self.chooseArray.count > 1) {
          // 创建加载图
          [self creatLoad];
            //调用 菜谱 网络请求
          [self connectionOfFoodBook:@"1"];

       }else
        {
            self.alert1 = [[[UIAlertView alloc]initWithTitle:@"提示" message:@"亲,至少要选两种!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil]autorelease];
            [self.alert1 show];
            [NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(timeAction) userInfo:nil repeats:NO];
        }
        if (self.chooseArray.count > 1) {
            [UIView animateWithDuration:1.0f animations:^{
                for (int i = 0; i < self.buttonArray.count; i++) {
         
                    MyFoodDaPei *button = [self.buttonArray objectAtIndex:i];
                    for (id alabel in [button subviews]) {
                        if ([alabel isKindOfClass:[UILabel class]]) {
                            UILabel *findLabel = (UILabel *)alabel;
                            if ([findLabel.text isEqualToString:@"x"]) {
                                [findLabel removeFromSuperview];
                                
                            }
                        }
                    }
                }
                self.downView .frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
                _chooseCollectView.frame = CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height - 40);
                //让右侧的tableView偏移回去
                self.tableView.frame = CGRectMake(self.view.frame.size.width, 0, 150, self.view.frame.size.height  - 40);
                self.imagev.frame = CGRectMake(self.view.frame.size.width - 30, (self.view.frame.size.height) / 2.0f , 30, 40);
                self.collectView.userInteractionEnabled = NO;
                self.collectView.alpha = 0.5;
                _imagev.image = [UIImage imageNamed:@"zheQi.png"];
                // 让确定的button 变成 "返回"
                [sender setTitle:@"返回" forState:UIControlStateNormal];
              }];
           }
     }
}
// 用食材 进行菜谱的网络请求
-(void)connectionOfFoodBook:(NSString *)page
{
    // page=1&methodName=SearchMix&size=15&material_ids=119%2C92%2C&version=4.02&
    NSString *myStr = @"";
    for (int i = 0; i < self.chooseArray.count; i++) {
        
        NSMutableDictionary *myaDic = [_chooseArray objectAtIndex:i];
        DaPeiModel *mymodel = [myaDic objectForKey:@"model"];
        myStr = [NSString stringWithFormat:@"%@%@%@",myStr,mymodel.Id,@"%2C"];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:page forKey:@"page"];
    [dic setObject:@"SearchMix" forKey:@"methodName"];
    [dic setObject:@"15" forKey:@"size"];
    [dic setObject:myStr forKey:@"material_ids"];
    [dic setObject:@"4.02" forKey:@"version"];
    
    // 查找能做多少菜的网络请求
      [self.hintLabel removeFromSuperview];
      [AsyncGetConnection asyncPOSTConnectionWithURL:@"http://api.izhangchu.com" parameters:dic block:^(NSData *data) {
          if ([page isEqualToString:@"1"]) {
              [self.findArray removeAllObjects];
          }
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic1 = [bigDic objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"data"];
        if ([[[self.findArray lastObject] title] isEqualToString:[[arr lastObject] objectForKey:@"title"]]) {
            [self.chooseCollectView footerEndRefreshing];

              return ;
          }
        for (NSDictionary *dic2 in arr) {
            SearchModel *model = [[SearchModel alloc]init];
            [model setValuesForKeysWithDictionary:dic2];
           
            model.description1 = [dic2 objectForKey:@"description"];
            [self.findArray addObject:model];
        }
        
        [self.hintLabel removeFromSuperview];
        if (self.findArray.count == 0 ) {
            self.hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.chooseCollectView.frame.size.height / 2.0f - 20, self.chooseCollectView.frame.size.width, 30)];
            [self.chooseCollectView addSubview:_hintLabel];
            _hintLabel.text = @"很抱歉,根据这些食材没找到相关菜谱!";
            _hintLabel.textAlignment = NSTextAlignmentCenter;
            _hintLabel.textColor = [UIColor grayColor];
            _hintLabel.font = [UIFont systemFontOfSize:15];
            
        }
        [self.chooseCollectView reloadData];
          [_HUD hide:YES];
          if ([page isEqualToString:@"1"]) {
                [self.chooseCollectView headerEndRefreshing];
          }
        [self.chooseCollectView footerEndRefreshing];
    }];

}

// tableView 协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      return self.ClassfileArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellName = @"cklala";
    ClassfileTableViewCell *mycell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!mycell) {
        mycell = [[ClassfileTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    
    if (self.ClassfileArray.count != 0 ) {
//        DaPeiClassfileModel *model = [self.ClassfileArray objectAtIndex:indexPath.row];
        [mycell receveModel:[self.ClassfileArray objectAtIndex:indexPath.row]];
    }
    
    return mycell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.playArray removeAllObjects];
    //取值
    [self.playArray addObjectsFromArray:[_collectArray objectAtIndex:indexPath.row]];
    //获得记录的数组
    self.tableCellRow = indexPath.row;
    
    [UIView animateWithDuration:1.0f animations:^{
        self.tableView.frame = CGRectMake(self.view.frame.size.width, 0, 150, self.view.frame.size.height  - 40);
        self.imagev.frame = CGRectMake(self.view.frame.size.width - 30, (self.view.frame.size.height) / 2.0f , 30, 40);
    }];
    self.collectView.userInteractionEnabled = YES;
    self.collectView.alpha = 1;
    _imagev.image = [UIImage imageNamed:@"zheQi.png"];

    // 重新加载
    [self.collectView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
